package com.cn.pet.util;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.*;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Excel 导出工具类
 */
public class ExcelUtil {

    /**
     * @param workbook
     * @param sheetNum  sheet的位置，0表示第一个sheet，多个sheet时从0按递增顺序添加
     * @param sheetName sheet的名称
     * @param headers   表格的标题
     * @param dataList  表格的数据
     * @throws Exception
     * @Description: 导出Excel的方法, 不支持合并单元格，如果columnData是long，输出数值
     */
    public static void exportExcel(Workbook workbook, int sheetNum, String sheetName, String[] headers, List<List<Object>> dataList) {

        Assert.notNull(workbook, "workbook对象不能为空");
        Assert.notNull(sheetName, "sheetName对象不能为空");
        Assert.notNull(headers, "headers对象不能为空");
        Assert.notNull(dataList, "data对象不能为空");
        // 生成一个表格
        Sheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetName);

        // 产生表格标题行
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell((short) i);
            RichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text.toString());
        }
        // 遍历集合数据，产生数据行
        if (!CollectionUtils.isEmpty(dataList)) {
            int index = 1;
            for (List<Object> rowData : dataList) {
                row = sheet.createRow(index);
                int cellIndex = 0;
                if (!CollectionUtils.isEmpty(rowData)) {
                    for (Object columnData : rowData) {
                        Cell cell = row.createCell((short) cellIndex);
                        if (columnData instanceof Long) {
                            cell.setCellValue(((Long) columnData).doubleValue());
                        } else {
                            cell.setCellValue(columnData == null ? "" : columnData.toString());
                        }
                        cellIndex++;
                    }
                    index++;
                }
            }
        }
    }

}


